package ua.at.tsvetkov.webservices;

import ua.at.tsvetkov.util.Log;

public class UrlBuilder {

	private StringBuilder	sb;
	private boolean	isNotFirst;

	public UrlBuilder(String rootUrl) {
		sb = new StringBuilder();
		sb.append(rootUrl);
		isNotFirst = false;
	}

	public static UrlBuilder builder(String root) {
		return new UrlBuilder(root);
	}

	
	public UrlBuilder addString(String value) {
		sb.append(value);
		return this;
	}

	public UrlBuilder addPair(String param, String value) {
		if (isNotFirst)
			sb.append('&');
		isNotFirst = true;
		sb.append(value);
		sb.append('=');
		sb.append(value);
		return this;
	}

	public UrlBuilder addPairs(String... param) {
		if (isOdd(param.length)) {
			Log.e(new Exception("Wrong param count. Must be multiple 2."));
		} else {
			for (int i = 0; i < param.length; i++) {
				if (isNotFirst)
					sb.append('&');
				sb.append(param[i++]);
				sb.append('=');
				sb.append(param[i]);
				isNotFirst = true;
			}
		}
		return this;
	}
	
	public String build() {
		return sb.toString();
	}

	private boolean isOdd(int val) {
		return (val & 1) != 0;
	}
}
